package com.woniu.darryringmall.utils;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ResponseUtils {
    //默认返回的静态变量，只能用于简单的返回成功或者失败
    public static final ResponseData SUCCESS = new ResponseData(ResultStateCode.SUCCESS, "操作成功");
    public static final ResponseData FAIL = new ResponseData(ResultStateCode.FAIL, "操作失败");

    /**
     * 接受三个参数返回一个封装好的数据
     * @param stateCode
     * @param msg
     * @param data
     * @return responseData
     */
    public static ResponseData<Object> getResponseData(int stateCode, String msg, Object data) {
        ResponseData<Object> responseData = new ResponseData<>(stateCode, msg);
        responseData.setData(data);
        return responseData;
    }

    /**
     * 将违反验证的错误消息处理并且返回一个属性消息的键值对Map
     * @param result
     * @return errorMap
     */
    public static Map<String, String> getErrorsMap(BindingResult result) {
        List<FieldError> fieldErrors = result.getFieldErrors();
        Map<String, String> errorMap = new HashMap<>();
        for (FieldError fieldError : fieldErrors) {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return errorMap;
    }
}
